<?php
namespace App\Services;

use App\Http\Controllers\common\BaseController;
use App\Models\api\House;
use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;

class EsService
{
    private $es;
    public function __construct()
    {
        //路径要保证和自己的目录一致
        $this->es = ClientBuilder::create()->setHosts([
            [
                'host'   => config('es.host'),
                'port'   => config('es.port'),
                'scheme' => config('es.scheme'),
                'user'   => config('es.user'),
                'pass'   => config('es.pass')
            ]
        ])->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
            ->setRetries(10)->build();
    }
    //创建es索引
    public function create_index($index,$field)
    {
        //创建索引
        $params=[
            'index'=>$index,
            'body'=>[
                'settings'=>[
                    'number_of_shards'=>5,//主分片数（分区）
                    'number_of_replicas'=>2//副本
                ],
                'mappings'=>[
                    '_source'=>[
                        'enabled'=>true
                    ],
                    //检索的字段
                    $field=>[
                        //字段名称
                        'truename'=>[
                            'type'=>'text',//类型
                            'analyzer' => 'ik_max_word',//分词器
                            'search_analyzer' => 'ik_max_word'//分词器
                        ]
                    ]
                ]
            ]
        ];
        $response = $this->es->indices()->create($params);
        if ($response){
          return true;
        }else{
            return false;
        }
    }
    // 添加文档
    public function add_doc($id, $doc, $index_name = 'house', $type_name = '_doc')
    {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id,
            'body' => $doc
        ];
        $response = $this->es->index($params);
        return $response;
    }

     //查询
    public function search_doc($key='house_name',$keywords = "电脑", $index_name = "house", $type_name = "app", $from = 0, $size = 5)
    {
        $params = [
            'index' =>$index_name,
            'body' => [
                'query' => [
                    'match' => [
                        $key => $keywords
                    ]
                ],
                'highlight' => [
                    'pre_tags' => ["<em style='color: red'>"],
                    'post_tags' => ["</em>"],
                    'fields' => [
                        $key => new \stdClass()
                    ]
                ]
            ]
        ];
        $response = $this->es->search($params);
        foreach ($response['hits']['hits'] as $k => $v){

            $v['_source'][$key] = $v['highlight'][$key][0];

            $Data[] = $v['_source'];
        }
        return BaseController::retJson(200,'ok',$Data);
    }
}
